/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Contributor(s):
 * Jiří Mašek
 *
 * ***** END LICENSE BLOCK ***** */


/**
 * Returns new created XUL element.
 *
 * @param tagName       tag name
 * @param attributes    attr1=val1|attr2=val2|attr3=val3
 *
 * @return  XUL element
 */

function createElement(tagName, attributes) {
    const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
    var item = document.createElementNS(XUL_NS, tagName);
    var attrs = attributes.split("|");

    for (i=0;i<attrs.length;i++) {
        attr = attrs[i].split("=");
        item.setAttribute(attr[0], attr[1]);
    }

    return item;
}
/*
function showElement(locator) {
    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
             .getService(Components.interfaces.nsIWindowMediator);
    var contentWindow = wm.getMostRecentWindow('navigator:browser').getBrowser()
                        .contentWindow;
    var pageBot = new MozillaBrowserBot(contentWindow);

    pageBot.getCurrentWindow = function() {
        return contentWindow;
    }

    try {
        var e = pageBot.findElement(locator);

        if (e) {
            var flasher = Components.classes["@mozilla.org/inspector/flasher;1"].createInstance()
                .QueryInterface(Components.interfaces.inIFlasher);
            flasher.color = "#ff0000";
            flasher.thickness = 2;
            flasher.invert = false;

            flasher.scrollElementIntoView(e);
            flasher.drawElementOutline(e);

            var flashIndex = 0;

            function animateFlasher() {
                var timeout = 0;
                if (flashIndex % 2 == 0) {
                    flasher.repaintElement(e);
                    timeout = 300;
                } else {
                    flasher.drawElementOutline(e);
                    timeout = 300;
                }
                flashIndex++;
                if (flashIndex < 3) {
                    setTimeout(animateFlasher, timeout);
                }
            }

            setTimeout(animateFlasher, 300);

        } else {
            LOG.error("locator not found: " + locator);
        }
    } catch (error) {
        LOG.error("locator not found: " + locator + ", error = " + error);
    }
}
*/

locateElementByXPath = function(xpath, inDocument, inWindow) {
    var results = eval_xpath(xpath, inDocument, {
        returnOnFirstMatch          : true,
        ignoreAttributesWithoutValue: false,
        allowNativeXpath            : true,
        xpathLibrary                : 'ajaxslt',
        namespaceResolver           : function(prefix) {
                                        if (prefix == 'html' || prefix == 'xhtml' || prefix == 'x') {
                                            return 'http://www.w3.org/1999/xhtml';
                                        } else if (prefix == 'mathml') {
                                            return 'http://www.w3.org/1998/Math/MathML';
                                        } else {
                                            throw new Error("Unknown namespace: " + prefix + ".");
                                        }
                                      }
    });
    return (results.length > 0) ? results : null;
};

function xpathMultipleResult() {
    var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
             .getService(Components.interfaces.nsIWindowMediator);
    var contentWindow = wm.getMostRecentWindow('navigator:browser').getBrowser()
                        .contentWindow;

    alert(locateElementByXPath("//a", contentWindow.document, contentWindow));
}

function addOwnTargetCandidates() {
    alert(window.editor.treeView.currentCommand.targetCandidates);

    //showElement(document.getElementById('commandTarget').value);

    var locators = [];

    locators.push("pause");
    locators.push("store");
    locators.push("echo");

    locators.sort();
            
    var types = [];

    types.push("pause");
    types.push("store");
    types.push("echo");

    types.sort();

    //Editor.GENERIC_AUTOCOMPLETE.setCandidates(XulUtils.toXPCOMString(this.editor.getAutoCompleteSearchParam("commandAction")),
    //                                          XulUtils.toXPCOMArray(commands));

    Editor.GENERIC_AUTOCOMPLETE.setCandidatesWithComments(XulUtils.toXPCOMString(this.editor.getAutoCompleteSearchParam("commandTarget")),
                                                          XulUtils.toXPCOMArray(locators),
                                                          XulUtils.toXPCOMArray(types));
}

function showStoredVars() {
    alert(start);
}

//var test = [];
//if ( test instanceof Array ) { }

function showElement(target) {
    window.editor.selDebugger.showElement = function(locator) {
	this.init();

        /* ********** REWRITE START ********** */
        this.runner.showElement = function(locator) {
            var wm = Components.classes['@mozilla.org/appshell/window-mediator;1'].getService(Components.interfaces.nsIWindowMediator);
            var contentWindow = wm.getMostRecentWindow("navigator:browser").getBrowser().contentWindow;
            var pageBot = new MozillaBrowserBot(contentWindow);
            pageBot.getCurrentWindow = function () {return contentWindow;};
            try {
                var e = pageBot.findElement(locator);
                /* ********** REWRITE START ********** */
                for(i in e) {
                    if (e[i]) {
                        var flasher = Components.classes['@mozilla.org/inspector/flasher;1'].createInstance().QueryInterface(Components.interfaces.inIFlasher);
                        flasher.color = "#ff0000";
                        flasher.thickness = 2;
                        flasher.invert = false;
                        flasher.scrollElementIntoView(e[i]);
                        flasher.drawElementOutline(e[i]);
                        var flashIndex = 0;

                        function animateFlasher() {
                            var timeout = 0;
                            if (flashIndex % 2 == 0) {
                                flasher.repaintElement(e[i]);
                                timeout = 300;
                            } else {
                                flasher.drawElementOutline(e[i]);
                                timeout = 300;
                            }
                            flashIndex++;
                            if (flashIndex < 3) {
                                setTimeout(animateFlasher, timeout);
                            }
                        }

                        setTimeout(animateFlasher, 300);
                    } else {
                        LOG.error("locator not found: " + locator);
                    }
                }
                /* ********** REWRITE END ********** */
            } catch (error) {
                LOG.error("locator not found: " + locator + ", error = " + error);
            }
        }
        /* ********** REWRITE END ********** */

        /* ********** REWRITE START ********** */
        this.runner.showElement = function(locator) {
            var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].getService(Components.interfaces.nsIWindowMediator);
            var contentWindow = wm.getMostRecentWindow('navigator:browser').getBrowser().contentWindow;
	
            //var pageBot = contentWindow._test_pageBot;
            //if (pageBot == null) {
            var pageBot = new MozillaBrowserBot(contentWindow);
            pageBot.getCurrentWindow = function() {
                return contentWindow;
            }
            //contentWindow._test_pageBot = pageBot;
            //}
            /* ********** REWRITE START ********** */
            pageBot.locateElementByXPath = function(xpath, inDocument, inWindow) {
                var results = eval_xpath(xpath, inDocument, {
                    returnOnFirstMatch          : true,
                    ignoreAttributesWithoutValue: this.ignoreAttributesWithoutValue,
                    allowNativeXpath            : this.allowNativeXpath,
                    xpathLibrary                : this.xpathLibrary,
                    namespaceResolver           : this._namespaceResolver
                });
                //return (results.length > 0) ? results[0] : null;
                return (results.length > 0) ? results : null;
            };
            pageBot.locationStrategies['xpath'] = this.locateElementByXPath;
            /* ********** REWRITE END ********** */

            try {
                var e = pageBot.findElement(locator);

                /* ********** REWRITE START ********** */
                for(i in e) {
                    if (e[i]) {
                        var flasher = Components.classes["@mozilla.org/inspector/flasher;1"].createInstance()
                                      .QueryInterface(Components.interfaces.inIFlasher);
                        flasher.color = "#88ff88";
                        flasher.thickness = 2;
                        flasher.invert = false;
            
                        flasher.scrollElementIntoView(e[i]);
                        flasher.drawElementOutline(e[i]);
            
                        var flashIndex = 0;

                        function animateFlasher() {
                            var timeout = 0;
                            if (flashIndex % 2 == 0) {
                                flasher.repaintElement(e[i]);
                                timeout = 300;
                            } else {
                                flasher.drawElementOutline(e[i]);
                                timeout = 300;
                            }
                            flashIndex++;
                            if (flashIndex < 3) {
                                setTimeout(animateFlasher, timeout);
                            }
                        }
            
                        setTimeout(animateFlasher, 300);

                    } else {
                        LOG.error("locator not found: " + locator);
                    }
                }
                /* ********** REWRITE END ********** */
            } catch (error) {
                LOG.error("locator not found: " + locator + ", error = " + error);
            }
        }
        /* ********** REWRITE END ********** */

	this.runner.showElement(locator);
    }

    window.editor.selDebugger.showElement(target);
}

document.getElementById("commandTarget").nextSibling.setAttribute("oncommand", "showElement(document.getElementById('commandTarget').value)");

// Pridani rozsirujiciho skriptu do nastaveni Selenium IDE

var path              = 'chrome://infocram6000/content/user-extension.js';
var userExtensionsURL = SeleniumIDE.Preferences.load()['userExtensionsURL']

if (userExtensionsURL.search(path) == -1) {
    var options = new Array();

    options['userExtensionsURL']  = userExtensionsURL;
    options['userExtensionsURL'] += userExtensionsURL.length == 0 ? path : ', ' + path;

    SeleniumIDE.Preferences.save(options);
}

// Pridani tlacitek do Selenium IDE

var vbox = document.getElementById("commandDetail");
var rows = vbox.getElementsByTagName("rows")[0];

var row = createElement("row", "align=center");

rows.insertBefore(row, rows.firstChild);

row.appendChild(createElement("button", "label=|oncommand=showStoredVars();"));
row.appendChild(createElement("button", "label=Vybrat element|oncommand=autopagerSelector.start(autopagerUtils.currentBrowser());"));

//document.getElementById('commandTarget').onchange = function() {}